package com.by_man.presenter.module_health_management.measure_blood_sugar;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.main_page.MainActivity;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.NetworkDataManager;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 测量血糖Activity
 * Created by man on 2017-02-17.
 */
public class MeasureBloodSugarActivity extends AppCompatActivity {
    private Handler handler;
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_measure_blood_sugar);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                initView();
            }
        };
        if (null == UserInfos.Three_BloodSugar_Record) { // 开启线程
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("提示信息");
            progressDialog.setMessage("正在请求数据，请稍后......");
            progressDialog.setCancelable(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();
            if (NetworkDataManager.ThereBSNum < 1) {  // 对此请求后，询问用户
                showRequestAgain();
            }
            Thread thread = new Thread() {
                public void run() {
                    while (null == UserInfos.Three_BloodSugar_Record) {  // 阻塞等待数据的初始化
                        if (NetworkDataManager.ThereBSNum< 1) {
                            showRequestAgain();
                        }
                    }
                    progressDialog.dismiss();
                    Message message = Message.obtain(handler);
                    message.sendToTarget();
                }
            };
            thread.setDaemon(true);             // 设置为守护线程
            thread.start();
        }
        else {
            initView();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_measure, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Intent intent = new Intent(this, MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
                onBackPressed();
                break;
            case R.id.action_check:
                Intent intent_B = new Intent(this, CheckBloodSugarActivity.class);
//                intent_B.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent_B);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, MainActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode,event);
//    }

//    protected void onRestart()
//    {
//        super.onRestart();
//        Intent intent=new Intent(this,GestureLockActivity.class);
//        intent.putExtra("class",this.getClass().getName());
//        intent.putExtra("position", 0);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
//    }

    private void initView(){
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        // 为button注册监听器
        Button manualBtn = (Button)findViewById(R.id.button_manual);
        Button deviceBtn = (Button)findViewById(R.id.button_device);

        manualBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MeasureBloodSugarActivity.this, ManualInputBSActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        deviceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        // 设置webview
        final WebView webViewBloodSugar = (WebView)findViewById(R.id.web_view_blood_sugar);
        webViewBloodSugar.getSettings().setJavaScriptEnabled(true);
        webViewBloodSugar.getSettings().setAppCacheEnabled(false);
        webViewBloodSugar.setWebViewClient(new WebViewClient());
        webViewBloodSugar.loadUrl(getResources().getString(R.string.bs_webview_loadaddress_week)
        + "?token=" + UserInfos.token);

        // 为radiogroup注册监听
        RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.week_record:
                        webViewBloodSugar.loadUrl(getResources().getString(R.string.bs_webview_loadaddress_week)
                                + "?token=" + UserInfos.token);
                        break;
                    case R.id.two_week_record:
                        webViewBloodSugar.loadUrl(getResources().getString(R.string.bs_webview_loadaddress_twoweek)
                                + "?token=" + UserInfos.token);
                        break;
                    case R.id.month_record:
                        webViewBloodSugar.loadUrl(getResources().getString(R.string.bs_webview_loadaddress_month)
                                + "?token=" + UserInfos.token);
                        break;
                    default:
                        break;
                }
            }
        });

        // 从服务器获取3条血糖记录
        final TextView bsView1 = (TextView)findViewById(R.id.blood_sugar_value1);
        final TextView bsView2 = (TextView)findViewById(R.id.blood_sugar_value2);
        final TextView bsView3 = (TextView)findViewById(R.id.blood_sugar_value3);

        final TextView type1 = (TextView)findViewById(R.id.type1);
        final TextView type2 = (TextView)findViewById(R.id.type2);
        final TextView type3 = (TextView)findViewById(R.id.type3);

        final TextView label1 = (TextView)findViewById(R.id.label1);
        final TextView label2 = (TextView)findViewById(R.id.label2);
        final TextView label3 = (TextView)findViewById(R.id.label3);

        final TextView showTime1 = (TextView)findViewById(R.id.showtime1);
        final TextView showTime2 = (TextView)findViewById(R.id.showtime2);
        final TextView showTime3 = (TextView)findViewById(R.id.showtime3);

        JSONArray jsonArray = LocalDataManager.getThreeBloodSugarRecord();
        if (null != jsonArray) {
            try {
                int i = jsonArray.length()/2;
                for(int m = 0; m<i; m++) {
                    if(m==0) {
                        JSONObject temp = (JSONObject) jsonArray.get(0);
                        bsView1.setText(temp.getString("value"));
                        showTime1.setText(temp.getString("updated_at").substring(0,16));
                        String tempType = temp.getString("type");
                        if (tempType.equalsIgnoreCase("null")) {
                            type1.setText("未知");
                        } else if (tempType.equalsIgnoreCase("0")) {
                            type1.setText("来自手动输入");
                        } else {
                            type1.setText("来自蓝牙输入");
                        }

                        JSONObject temp3 = (JSONObject) jsonArray.get(m+i);
                        label1.setText(temp3.getString("value"));
                    }

                    if(m==1) {

                        JSONObject temp1 = (JSONObject) jsonArray.get(1);
                        bsView2.setText(temp1.getString("value"));
                        // biaoqian2.setText(temp1.getString("12"));
                        showTime2.setText(temp1.getString("updated_at").substring(0,16));
                        String tempType1 = temp1.getString("type");
                        if (tempType1.equalsIgnoreCase("null")) {
                            type2.setText("未知");
                        } else if (tempType1.equalsIgnoreCase("0")) {
                            type2.setText("来自手动输入");
                        } else {
                            type2.setText("来自蓝牙输入");
                        }

                        JSONObject temp5 = (JSONObject) jsonArray.get(m+i);
                        label2.setText(temp5.getString("value"));
                    }

                    if(m==2) {
                        JSONObject temp2 = (JSONObject) jsonArray.get(2);
                        bsView3.setText(temp2.getString("value"));
                        // biaoqian3.setText(temp2.getString("12"));
                        showTime3.setText(temp2.getString("updated_at").substring(0,16));
                        String tempType2 = temp2.getString("type");
                        if (tempType2.equalsIgnoreCase("null")) {
                            type3.setText("未知");
                        } else if (tempType2.equalsIgnoreCase("0")) {
                            type3.setText("来自手动输入");
                        } else {
                            type3.setText("来自蓝牙输入");
                        }

                        JSONObject temp6 = (JSONObject) jsonArray.get(m+i);
                        label3.setText(temp6.getString("value"));
                    }

                    // 进行缓存操作

                }
            } catch (JSONException je) {
                je.printStackTrace();
            }
        }
    }

    public void showRequestAgain() {
        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this).setTitle("提醒")
                .setMessage("已多次请求服务器，是否继续请求？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        NetworkDataManager.ThereBSNum = 3;
                        LocalDataManager.getThreeBloodSugarRecord();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
